﻿using MSSClient.Model;
using MSSClient.Utils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using TestTreeView.Model;

namespace MSSClient
{
    /// <summary>
    /// Interaction logic for ResultDlg.xaml
    /// </summary>
    public partial class ResultDbDlg : Window
    {
        public FileSystemWatcher watcher = new FileSystemWatcher();
        /// <summary>
        /// 上传成功列表       
        /// </summary>
        public ResultDbDlg(List<Model.ResultModel> list, List<Model.ResultModel> nowList)
        {
            InitializeComponent();
           
            if (null == list)
            {
                return;
            }
            //排序后的数组
            List<ResultModel> resultModelList = new List<ResultModel>();
            for (int i = list.Count - 1; i >= 0; i--)
            {
                ResultModel resultModel = new ResultModel();
                resultModel = list[i];
                resultModelList.Add(resultModel);
            }
            int SucceseListIndex = 1;
            int FailListIndex = 1;
            int NowSucceseListIndex = 1;
            int upLoadListIndex = 1;
            int NowFailListIndex = 1;
            foreach (Model.ResultModel group in resultModelList)
            {
                SucceseListItem item = new SucceseListItem { Group = group.imageCode, Count = group.count, Status = group.uploadResult, Date = group.date };

                if (group.logMark == 1)
                {
                    item.Index = SucceseListIndex;
                    SucceseListIndex++;
                    SucceseList.Items.Add(item);
                }
                if (group.logMark == 2)
                {
                    item.Index = FailListIndex;
                    FailListIndex++;
                    FailList.Items.Add(item);
                }
            }
            foreach (Model.ResultModel group in nowList)
            {
                SucceseListItem item = new SucceseListItem { Group = group.imageCode, Count = group.count, Status = group.uploadResult, Date = group.date };

                if (group.logMark == 1)
                {
                    item.Index = NowSucceseListIndex;
                    NowSucceseList.Items.Add(item);
                }
                if (group.logMark == 2)
                {
                    item.Index = NowFailListIndex;
                    NowFailListIndex++;
                    NowFailList.Items.Add(item);
                }
                item.Index = upLoadListIndex;
                upLoadList.Items.Add(item);
                upLoadListIndex++;
            }

            if (File.Exists(@"C:\MssClientCache\progress.txt"))
            {
                WatcherStrat(@"C:\MssClientCache\", "progress.txt", true, true);
                string txt = File.ReadAllText(@"C:\MssClientCache\progress.txt");
                if (txt == "")
                {
                    progressTxet.Dispatcher.Invoke(new Action(() =>
                    {
                        this.progressTxet.Content = "空闲";
                    }));
                }
                else
                {
                    progressTxet.Dispatcher.Invoke(new Action(() =>
                    {
                        this.progressTxet.Content = txt;
                    }));
                }
            }
        }

        /// <summary>
        /// 初始化监听
        /// </summary>
        /// <param name="StrWarcherPath">需要监听的目录</param>
        /// <param name="FilterType">需要监听的文件类型(筛选器字符串)</param>
        /// <param name="IsEnableRaising">是否启用监听</param>
        /// <param name="IsInclude">是否监听子目录</param>
        private  void WatcherStrat(string StrWarcherPath, string FilterType, bool IsEnableRaising, bool IsInclude)
        {
            watcher.BeginInit();
            //设置监听文件类型
            watcher.Filter = FilterType;
            //设置是否监听子目录
            watcher.IncludeSubdirectories = IsInclude;
            //设置是否启用监听?
            watcher.EnableRaisingEvents = IsEnableRaising;
            //设置需要监听的更改类型(如:文件或者文件夹的属性,文件或者文件夹的创建时间;NotifyFilters枚举的内容)
            watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;
            //设置监听的路径
            watcher.Path = StrWarcherPath;
            //注册创建文件或目录时的监听事件
            //watcher.Created += new FileSystemEventHandler(watch_created);
            //注册当指定目录的文件或者目录发生改变的时候的监听事件
            watcher.Changed += new FileSystemEventHandler(watch_changed);
            //注册当删除目录的文件或者目录的时候的监听事件
            //watcher.Deleted += new FileSystemEventHandler(watch_deleted);
            //当指定目录的文件或者目录发生重命名的时候的监听事件
            //watcher.Renamed += new RenamedEventHandler(watch_renamed);
            watcher.EndInit();
        }

        /// <summary>
        /// 当指定目录的文件或者目录发生改变的时候的监听事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void watch_deleted(object sender, FileSystemEventArgs e)
        {
            try
            {
                //shuaxin_Button.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                //this.Close();
                //flashData();
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                return;
            }
        }

        private void watch_changed(object sender, FileSystemEventArgs e)
        {
            try
            {
                System.Threading.Thread.Sleep(150);//等待150毫秒给文件写入操作
                string txt = File.ReadAllText(e.FullPath);
                progressTxet.Dispatcher.Invoke(new Action(() =>
                {
                    this.progressTxet.Content = txt;
                }));
                Console.WriteLine(txt);
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                return;
            }
        }

        private void queding_Button_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void tabControl1_SelectionChanged(object sender, RoutedEventArgs e)
        {
            //if(tabControl1.SelectedItem == tabItem1) quxiao_Button.IsEnabled = true; 
        }

        private void NowFailList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ClipboardFunction(NowFailList);
        }

        private void upLoadList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ClipboardFunction(upLoadList);
        }
        private void SucceseList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ClipboardFunction(SucceseList);
        }
        private void NowSucceseList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ClipboardFunction(NowSucceseList);
        }
        private void FailList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ClipboardFunction(FailList);
        }

        private void reflash_Click(object sender, RoutedEventArgs e)
        {
            Close();
            flashData();
        }

        /// <summary>
        /// 刷新数据
        /// </summary>
        public void flashData()
        {
            //读取文件流对象
            string userNameFilePath = "C:/MssClientCache/";//缓存保存地址
            if (!Directory.Exists(userNameFilePath))//判断文件夹是否存在 
            {
                return;//不存在就不执行下面
            }

            string fileNameNow = CommonUtil.readUserInfo() + "_nowUploadResultData.bin";
            string fileName = CommonUtil.readUserInfo() + "_resultData.bin";
            string filePath = "C:/MssClientCache/";

            // 登录时 如果没有resultData.bin文件就创建、有就打开
            FileStream fs = new FileStream(filePath + fileName, FileMode.OpenOrCreate);
            FileStream fsNow = new FileStream(filePath + fileNameNow, FileMode.OpenOrCreate);
            List<ResultModel> list = new List<ResultModel>();
            List<ResultModel> nowList = new List<ResultModel>();
            if (fs.Length > 0)
            {
                BinaryFormatter bf = new BinaryFormatter();

                Dictionary<string, ResultModel> ResultList;
                Dictionary<string, ResultModel> nowUploadResultList;
                ResultList = bf.Deserialize(fs) as Dictionary<string, ResultModel>;
                List<GroupModel> tempList = new List<GroupModel>();
                if (ResultList.Count != 0)
                {
                    foreach (ResultModel group in ResultList.Values)
                    {
                        list.Add(group);
                    }
                }
                if (fsNow.Length > 0)
                {
                    nowUploadResultList = bf.Deserialize(fsNow) as Dictionary<string, ResultModel>;
                    fsNow.Close();
                    if (nowUploadResultList.Count != 0)
                    {
                        foreach (ResultModel group in nowUploadResultList.Values)
                        {
                            nowList.Add(group);
                        }
                    }
                }
                if (null == list)
                {
                    return;
                }
                //排序后的数组
                List<ResultModel> resultModelList = new List<ResultModel>();

                for (int i = list.Count - 1; i >= 0; i--)
                {
                    ResultModel resultModel = new ResultModel();
                    resultModel = list[i];
                    resultModelList.Add(resultModel);
                }
                int SucceseListIndex = 1;
                int FailListIndex = 1;
                int NowSucceseListIndex = 1;
                int upLoadListIndex = 1;
                int NowFailListIndex = 1;
                foreach (Model.ResultModel group in resultModelList)
                {
                    SucceseListItem item = new SucceseListItem { Group = group.imageCode, Count = group.count, Status = group.uploadResult, Date = group.date };

                    if (group.logMark == 1)
                    {
                        item.Index = SucceseListIndex;
                        SucceseListIndex++;
                        SucceseList.Items.Add(item);
                    }
                    if (group.logMark == 2)
                    {
                        item.Index = FailListIndex;
                        FailListIndex++;
                        FailList.Items.Add(item);
                    }
                }
                foreach (Model.ResultModel group in nowList)
                {
                    SucceseListItem item = new SucceseListItem { Group = group.imageCode, Count = group.count, Status = group.uploadResult, Date = group.date };

                    if (group.logMark == 1)
                    {
                        item.Index = NowSucceseListIndex;
                        NowSucceseList.Items.Add(item);
                    }
                    if (group.logMark == 2)
                    {
                        item.Index = NowFailListIndex;
                        NowFailListIndex++;
                        NowFailList.Items.Add(item);
                    }
                    item.Index = upLoadListIndex;
                    upLoadList.Items.Add(item);
                    upLoadListIndex++;
                }
                ResultDbDlg dlg = new ResultDbDlg(list, nowList);
                dlg.Show();
            }
            else
            {
                ResultDbDlg dlg = new ResultDbDlg(list, nowList);
                dlg.Show();
            }
            fs.Close();
            fsNow.Close();
        }

        /// <summary>
        /// 复制数据到剪切板
        /// </summary>
        /// <param name="list"></param>
        public void ClipboardFunction(ListView list)
        {
            try
            {
                
                string groupStr = "";
                IList listBox = list.SelectedItems;
                foreach (SucceseListItem group in listBox)
                {
                    groupStr = group.Group;
                }
                Clipboard.SetDataObject(groupStr);
                CommonUtil.ShowMsgFrom("内容:[" + groupStr + "]已经复制到剪贴板");
            }
            catch (System.Exception ex)
            {
                CommonUtil.WriteLog(ex);
                return;
            }
        }

        private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            MSSWindow mss = new MSSWindow();
            this.Height = mss.Height * 0.8;
            this.Width = mss.Width * 0.8;
        }
    }

    //上传成功列表实体
    public class SucceseListItem
    {
        public int Index { get; set; }
        public string Group { get; set; }
        public int Count { get; set; }
        public string Status { get; set; }
        public string Date { get; set; }
    }

    //待上传列表实体
    public class upLoadListItem
    {
        public int Index { get; set; }
        public string Group { get; set; }
        public int Count { get; set; }
        public string Status { get; set; }
    }
    //上传失败列表实体
    public class FailListItem
    {
        public int Index { get; set; }
        public string Group { get; set; }
        public int Count { get; set; }
        public string Status { get; set; }
        public string Date { get; set; }
    }
}
